from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client

from django.conf import settings

from qcloud_cos.cos_exception import CosServiceError


def delete_bucket(bucket_name, region):
    """ 删除 项目桶 """

    secret_id = 'AKID0qVK4f4FCtOgkbGm5A2g5GE2f7RYR5Ug'
    secret_key = '2sVdbMyPdfT5WmpfIm6D8pOmwsNtCJEx'

    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    client = CosS3Client(config)

    # 根据腾讯cos的要求，删除桶必须前清空桶
    try:  # 防止删除不存在的桶cos报错
        # 1. 删除所有的桶文件
        while True:
            part_objects = client.list_objects(bucket_name)

            # 已经删除完毕，获取不到值
            contents = part_objects.get('Contents')
            if not contents:
                break

            # 批量删除
            objects = {
                "Quiet": "true",
                "Object": [{'Key': item["Key"]} for item in contents]
            }
            client.delete_objects(bucket_name, objects)

            if part_objects['IsTruncated'] == "false":
                break

        # 2. 删除所有的桶碎片
        while True:
            part_uploads = client.list_multipart_uploads(bucket_name)
            uploads = part_uploads.get('Upload')
            if not uploads:
                break
            for item in uploads:
                client.abort_multipart_upload(bucket_name, item['Key'], item['UploadId'])
            if part_uploads['IsTruncated'] == "false":
                break

        # 3. 删除空桶
        client.delete_bucket(bucket_name)
    except CosServiceError as e:
        pass


if __name__ == '__main__':
    delete_bucket(bucket_name='test-1316848700', region='ap-chengdu')
